<template>
  <el-col :class="className" :span="span">
    <template v-if="field && formData">
      <el-form-item :label="field.label" :prop="field.prop" v-bind="$attrs">
        <!-- 输入框 -->
        <el-input v-if="field.type == 'input'" v-model="formData[field.prop]" :clearable="field.clearable" :placeholder="field.placeholder" :type="field.inputType"/>
        <!-- 自定义字典下拉选择 -->
        <DictSelect v-if="field.type == 'dict-select'" v-model="formData[field.prop]" :dict-type="field.dictType || ''" :placeholder="field.placeholder"/>
      </el-form-item>
    </template>
    <el-form-item v-else v-bind="$attrs">
      <slot/>
    </el-form-item>
  </el-col>
</template>

<script lang="ts" setup>
import { computed, getCurrentInstance, inject, onMounted, onUnmounted, PropType, reactive, } from 'vue';
import { formContextKey, FormItemData, QueryFormItemRule, QueryFormProvide, } from '@/components/query-form/constants';
import { DictSelect } from '@/components/dict-select';

defineOptions({
  inheritAttrs: false,
  name: 'QueryFormItem',
});

const props = defineProps({
  field: {
    type: Object as PropType<QueryFormItemRule>,
  },
  formData: {
    type: Object,
  },
  colMultiple: {
    type: Number,
    default: 1
  }
});

const instance = getCurrentInstance();

const formItem = reactive<FormItemData>({
  uid: instance?.uid!,
  index: null,
  visible: false,
});

const formContext = inject(formContextKey) as QueryFormProvide;

const className = computed(() => {
  return ['query-form-item', formItem.visible ? 'col-hide' : ''];
});

const span = computed(() => {
  const {span} = formContext.form.value;
  if (span < 12) {
    return span * (props.colMultiple || props.field?.colMultiple || 1.0);
  }
  return span;
});

onMounted(() => {
  formContext.registerForm(formItem);
});

onUnmounted(() => {
  formContext.unregisterForm(formItem.uid);
});
</script>

<style lang="scss" scoped>
.col-hide {
  display: none;
}
</style>
